<template>
  <div v-loading="loading" class="app-container">
    <div class="head-container">
      <el-form :model="params" class="searchform" :inline="true" size="mini" label-width="auto">
        <el-form-item label="UPC">
          <el-input v-model="params.upcNbr" placeholder="输入UPC查询" clearable style="width: 200px;" />
        </el-form-item>
        <el-form-item label="门店号">
          <el-input v-model="params.storeNbr" placeholder="输入门店号查询" clearable style="width: 200px;" />
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" style="float:right;margin-right:0px;" icon="el-icon-refresh" round @click="resetForm">重置</el-button>
          <el-button size="mini" type="primary" style="float:right;margin-right:0px;" icon="el-icon-search" round @click="toQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="padding-top:5px">
      <el-button size="mini" type="primary" style="float:right;margin-left:0px;" round @click="doDownloadTemplate">模板下载</el-button>
      <el-upload
        ref="upload"
        :auto-upload="false"
        :on-change="handleFileChange"
        :show-file-list="false"
        :limit="1"
        :multiple="false"
        action="#"
        accept=""
        style="float:right;margin-left:0px;"
      >
        <el-button size="mini" type="primary" round>批量新增导入</el-button>
      </el-upload>
      <el-button size="mini" type="primary" style="float:right;margin-left:0px;" round @click="batchDelete">批量删除</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-left:0px;" round @click="doClearSelection">取消选择</el-button>
      <el-table ref="dataTab" :data="data" :row-key="getRowKeys" stripe size="mini" border style="width: 100%;" @header-dragend="colChange" @selection-change="handleSelectionChange">
        <el-table-column :reserve-selection="true" type="selection" align="center" width="55" />
        <el-table-column :show-overflow-tooltip="true" label="条码" prop="upcNbr" :width="colWidths.upcNbr">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="toEdit(scope.row)">{{ scope.row.upcNbr }}</el-button>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="门店号" prop="storeNbr" :width="colWidths.storeNbr" />
        <el-table-column :show-overflow-tooltip="true" label="生效时间" prop="startTime" :width="colWidths.startTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') + ' 至 ' + parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="创建人" prop="createdBy" :width="colWidths.createdBy" />
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page.sync="currentPage"
        :page-sizes="[50,100,500]"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
    </div>
    <el-dialog
      v-loading="loading"
      :visible.sync="dialog"
      title="白名单编辑"
      width="700px"
      :close-on-click-modal="false"
      append-to-body
      @close="cancel"
    >
      <div>
        <el-form ref="dataForm" :model="whiteObj" size="small" label-width="180px">
          <el-form-item label="UPC：" prop="upcNbr">
            <span>{{ whiteObj.upcNbr }}</span>
          </el-form-item>
          <el-form-item label="门店号：" prop="storeNbr">
            <span>{{ whiteObj.storeNbr }}</span>
          </el-form-item>
          <el-form-item label="生效时间">
            <el-date-picker
              v-model="effTimes"
              size="mini"
              type="daterange"
              format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="effTimeChange"
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button type="primary" @click="doSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { parseTime } from '@/utils/index'
import initData from '@/api/olm/initData'
import { importUpcWhiteListData, batchDelete, update } from '@/api/olm/whiteList'
import { getDownLoadTemplateUrl } from '@/api/plugs'
import { authentication } from '@/utils/processingData.js'

export default {
  mixins: [initData],
  data() {
    return {
      ids: [],
      loading: false,
      dialog: false,
      whiteObj: {},
      effTimes: []
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    parseTime,
    beforeInit() {
      this.url = process.env.VUE_APP_BASE_API3 + '/upcWhiteList/queryPageList'
      this.params.pageNum = this.page
      this.params.pageSize = this.size
      return true
    },
    // 查询
    toQuery() {
      this.page = 0
      this.currentPage = 1
      this.init()
      this.doClearSelection()
    },
    // 查询栏重置触发
    resetForm() {
      this.params = {}
    },
    // 列表多选框触发
    handleSelectionChange(val) {
      this.ids = []
      val.forEach(item => {
        this.ids.push(item.id)
      })
    },
    // 翻页选择row的key值
    getRowKeys(row) {
      return row.id
    },
    // 清空选择项
    doClearSelection() {
      this.$refs.dataTab.clearSelection()
      this.ids = []
    },
    // 文件变动的钩子-附件上传
    handleFileChange(file, fileList) {
      if (!(file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
        Message({
          message: '请上传格式为 xlsx 的Excel文件。',
          type: 'warning',
          duration: 3 * 1000
        })
        fileList.pop()
      }
      var size = file.size / 1024 / 1024
      if (size > 5) {
        Message({
          message: '文件大小必须小于5M。',
          type: 'warning',
          duration: 3 * 1000
        })
        fileList.pop()
      } else {
        this.$confirm('是否批量新增？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          var formData = new FormData()
          formData.append('file', file.raw)
          importUpcWhiteListData(formData).then(_ => {
            this.loading = false
            this.toQuery()
            Message({
              message: '上传成功。',
              type: 'success',
              duration: 3 * 1000
            })
          }, error => {
            console.log(error)
            this.loading = false
          })
          fileList.pop()
        })
      }
    },
    batchDelete() {
      if (this.ids.length < 1) {
        Message({
          message: '请选择需要删除的白名单数据。',
          type: 'warning',
          duration: 3 * 1000
        })
        return
      }
      this.$confirm('是否批量删除白名单？数量：' + this.ids.length, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        batchDelete({ ids: this.ids }).then(_ => {
          this.loading = false
          this.toQuery()
          Message({
            message: '操作成功。',
            type: 'success',
            duration: 3 * 1000
          }, error => {
            console.log(error)
            this.loading = false
          })
        })
      })
    },
    toEdit(whiteObj) {
      this.whiteObj = whiteObj
      this.effTimes = [this.whiteObj.startTime, this.whiteObj.endTime]
      this.dialog = true
    },
    doSubmit() {
      this.loading = true
      update(this.whiteObj).then(_ => {
        this.loading = false
        this.toQuery()
        this.cancel()
        Message({
          message: '操作成功。',
          type: 'success',
          duration: 3 * 1000
        }, error => {
          console.log(error)
          this.loading = false
        })
      })
    },
    effTimeChange() {
      this.whiteObj.startTime = this.effTimes[0]
      this.whiteObj.endTime = this.effTimes[1]
    },
    cancel() {
      this.dialog = false
      this.whiteObj = {}
    },
    // 模板下载
    doDownloadTemplate() {
      var val = '?changeType=301&templateType=4'
      getDownLoadTemplateUrl(val).then(res => {
        if (res) {
          window.open(authentication(res))
        } else {
          Message({
            message: '未找到模板请模板维护',
            type: 'warning',
            duration: 2 * 1000
          })
        }
      })
    }
  }
}
</script>

